<template>
  <div class="dashboard">
    <div class="card vitals-card">
      <h2>生命体征</h2>
      <div class="chart-container">
        <canvas ref="vitalsChart"></canvas>
      </div>
      <div class="vitals-summary">
        <div class="summary-item">
          <span class="label">心率:</span>
          <span class="value">{{ currentHeartRate }} bpm</span>
        </div>
        <div class="summary-item">
          <span class="label">呼吸:</span>
          <span class="value">{{ currentBreathRate }} bpm</span>
        </div>
      </div>
    </div>
    
    <div class="card environment-card">
      <h2>环境数据</h2>
      <div class="environment-data">
        <div class="data-item">
          <span class="label">温度:</span>
          <strong>{{ environment.temperature }}°C</strong>
        </div>
        <div class="data-item">
          <span class="label">湿度:</span>
          <strong>{{ environment.humidity }}%</strong>
        </div>
        <div class="data-item">
          <span class="label">光照:</span>
          <strong>{{ environment.light }} lux</strong>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Chart from 'chart.js/auto'
import api from '../api'

export default {
  name: 'Dashboard',
  data() {
    return {
      vitalsChart: null,
      heartRateData: [72, 73, 74, 73, 72],
      breathRateData: [16, 16, 17, 16, 16],
      timeLabels: ['1分钟前', '45秒前', '30秒前', '15秒前', '当前'],
      currentHeartRate: 72,
      currentBreathRate: 16,
      environment: {
        temperature: 24,
        humidity: 45,
        light: 500
      },
      updateInterval: null
    }
  },
  mounted() {
    this.initChart()
    this.fetchData()
    
    // 每5秒更新一次数据
    this.updateInterval = setInterval(() => {
      this.fetchData()
    }, 5000)
  },
  beforeDestroy() {
    // 清除定时器
    if (this.updateInterval) {
      clearInterval(this.updateInterval)
    }
    
    // 销毁图表
    if (this.vitalsChart) {
      this.vitalsChart.destroy()
    }
  },
  methods: {
    initChart() {
      const ctx = this.$refs.vitalsChart.getContext('2d')
      this.vitalsChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: this.timeLabels,
          datasets: [
            {
              label: '心率',
              data: this.heartRateData,
              borderColor: '#e74c3c',
              backgroundColor: 'rgba(231, 76, 60, 0.1)',
              tension: 0.4,
              fill: true
            },
            {
              label: '呼吸',
              data: this.breathRateData,
              borderColor: '#3498db',
              backgroundColor: 'rgba(52, 152, 219, 0.1)',
              tension: 0.4,
              fill: true
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: false,
              title: {
                display: true,
                text: '数值'
              }
            },
            x: {
              title: {
                display: true,
                text: '时间'
              }
            }
          }
        }
      })
    },
    updateChart() {
      if (this.vitalsChart) {
        this.vitalsChart.data.labels = this.timeLabels
        this.vitalsChart.data.datasets[0].data = this.heartRateData
        this.vitalsChart.data.datasets[1].data = this.breathRateData
        this.vitalsChart.update()
      }
    },
    async fetchData() {
      try {
        // 这里会调用API获取真实数据
        // 在实际项目中取消注释下面的代码
        
        /*
        const vitalsData = await api.getVitalSigns()
        this.heartRateData = vitalsData.heartRate
        this.breathRateData = vitalsData.respiration
        this.currentHeartRate = vitalsData.currentHeartRate
        this.currentBreathRate = vitalsData.currentBreathRate
        
        const envData = await api.getEnvironmentData()
        this.environment = envData
        */
        
        // 模拟数据更新
        this.simulateDataUpdate()
        
        // 更新图表
        this.updateChart()
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    },
    simulateDataUpdate() {
      // 生成模拟数据
      const randomHeartRate = Math.floor(Math.random() * 10) + 65
      const randomBreathRate = Math.floor(Math.random() * 5) + 14
      
      // 更新心率数据
      this.heartRateData.push(randomHeartRate)
      if (this.heartRateData.length > 5) {
        this.heartRateData.shift()
      }
      this.currentHeartRate = randomHeartRate
      
      // 更新呼吸数据
      this.breathRateData.push(randomBreathRate)
      if (this.breathRateData.length > 5) {
        this.breathRateData.shift()
      }
      this.currentBreathRate = randomBreathRate
      
      // 更新时间标签
      const now = new Date()
      const timeStr = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`
      this.timeLabels.push(timeStr)
      if (this.timeLabels.length > 5) {
        this.timeLabels.shift()
      }
      
      // 更新环境数据
      this.environment.temperature = (Math.random() * 2 + 23).toFixed(1)
      this.environment.humidity = Math.floor(Math.random() * 10 + 40)
      this.environment.light = Math.floor(Math.random() * 200 + 400)
    }
  }
}
</script>

<style scoped>
.dashboard {
  display: grid;
  gap: 20px;
  grid-template-columns: 1fr;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #374151;
  font-size: 1.2em;
}

.chart-container {
  height: 300px;
  margin-bottom: 20px;
}

.vitals-summary {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.summary-item {
  background: #f8f9fa;
  padding: 10px 15px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.label {
  color: #6b7280;
}

.value {
  font-weight: bold;
  color: #1f2937;
}

.environment-data {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
}

.data-item {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
  display: flex;
  flex-direction: column;
}

.data-item .label {
  margin-bottom: 5px;
}

.data-item strong {
  font-size: 1.5rem;
  font-weight: bold;
  color: #2c3e50;
}

/* 媒体查询 - 大屏幕布局 */
@media (min-width: 768px) {
  .dashboard {
    grid-template-columns: 2fr 1fr;
  }
  
  .vitals-card {
    grid-column: 1;
  }
  
  .environment-card {
    grid-column: 2;
    grid-row: 1;
  }
}
</style>
